import { lib, game, ui, get, ai, _status } from '../../../noname.js';
import { swTool } from '../main/swTool.js'

lib.element.content.replaceHandcardsOL = function () {
	'step 0'
	event.players = event.players.filter(p => {
		return p === game.me || (p.ws && p.isOnline2())//人机就不给刷牌了
	})
	event.players.forEach(p => {
		if (!p.replaceHandcardsnum) {
			p.replaceHandcardsnum = 0
			p.send(() => { game.me.replaceHandcardsnum = 0 })
		}
	})
	'step 1'
	var sendback = function (result, player) {
		if ((result && result.bool === false && event)) {
			event.players.remove(player)
		}
		if (result && result.bool) {
			player.send(() => { game.me.replaceHandcardsnum++ })
			player.replaceHandcardsnum++
			/*otherPile主要是针对那些用专属牌堆，不从一般牌堆摸牌的角色（如陈寿），该属性目前只有两个键值对，且都为函数
			 *getCards函数与获得牌相关，只传入要获得的牌数num作为参数
			 *discard与手气卡换牌后弃置牌相关，只传入要弃置的牌card作为参数
			 */
			const hs = player.getCards("h"),
				cards = [],
				otherGetCards = event.otherPile?.[player.playerid]?.getCards,
				otherDiscacrd = event.otherPile?.[player.playerid]?.discard;
			//先弃牌
			game.broadcastAll(
				function (player, hs, otherDiscacrd) {
					game.addVideo("lose", player, [get.cardsInfo(hs), [], [], []]);
					for (var i = 0; i < hs.length; i++) {
						hs[i].removeGaintag(true);
						if (otherDiscacrd) otherDiscacrd(hs[i]);
						else hs[i].discard(false);
					}
				},
				player,
				hs,
				otherDiscacrd
			);
			//再摸牌，先看有没有专属牌堆
			if (otherGetCards) cards.addArray(otherGetCards(hs.length));
			else cards.addArray(get.cards(hs.length));
			//添加标记相关
			//event.gaintag支持函数、字符串、数组。数组就是添加一连串的标记；函数的返回格式为[[cards1,gaintag1],[cards2,gaintag2]...]
			if (event.gaintag?.[player.playerid]) {
				const gaintag = event.gaintag[player.playerid];
				const list = typeof gaintag == "function" ? gaintag(hs.length, cards) : [[cards, gaintag]];
				game.broadcastAll(
					(player, list) => {
						for (let i = list.length - 1; i >= 0; i--) {
							player.directgain(list[i][0], null, list[i][1]);
						}
					},
					player,
					list
				);
			} else player.directgain(cards);
			player._start_cards = cards;
		}
	};
	for (var i = 0; i < event.players.length; i++) {
		if (event.players[i].isOnline()) {
			event.withol = true;
			event.players[i].send(allnum => {
					const num = allnum - game.me.replaceHandcardsnum
					game.me.chooseBool(`是否置换手牌？（还剩${num}次）`).set('ai', () => false)
					game.resume()
				},
				lib.config[`${swTool.myURL()}func_replaceHandCards`]
			);
			event.players[i].wait(sendback);
		} else if (event.players[i] == game.me) {
			event.withme = true;
			const num = lib.config[`${swTool.myURL()}func_replaceHandCards`] - game.me.replaceHandcardsnum
			game.me.chooseBool(`是否置换手牌？（还剩${num}次）`);
			game.me.wait(sendback);
		}
	}
	'step 2'
	if (event.withme) {
		game.me.unwait(result);
	}
	'step 3'
	if (event.withol && !event.resultOL) {
		game.pause();
	}
	'step 4'
	event.players = event.players.filter(p => p === game.me || (p.ws && p.isOnline2()))
	if (event.players.length > 0 && swTool.replaceHandcardsnum < lib.config[`${swTool.myURL()}func_replaceHandCards`]) {
		event.goto(1)
		swTool.replaceHandcardsnum++
		delete event.resultOL
	}
}

lib.element.player.chooseItem = function() {
	var next = game.createEvent("chooseItem");
	next.player = this;
	for (var i = 0; i < arguments.length; i++) {
		if (typeof arguments[i] == "boolean") {
			next.forced = arguments[i];
		} else if (typeof arguments[i] == "string") {
			next.prompt = arguments[i];
		}
	}
	next.setContent("chooseItem");
	next.filterOk = function () {
		return true;
	};
	next.filterMove = function () {
		return true;
	};
	return next;
}
lib.element.content.chooseItem = async function(event, trigger, player) {
	if (event.chooseTime && _status.connectMode && !game.online) {
		event.time = lib.configOL.choose_timeout;
		game.broadcastAll(time => {
			lib.configOL.choose_timeout = time;
		}, event.chooseTime);
	}

	let result;
	if (event.isMine()) {
		result = await new Promise(resolve => {
			delete ui.selected.guanxing_button;

			const list = event.list;
			const filterMove = event.filterMove;
			const filterOk = event.filterOk;

			//_status.imchoosing = true;
			event.settleed = false;

			event.dialog = ui.create.dialog(event.prompt || "请选择要操作的牌", "hidden", "forcebutton");

			event.switchToAuto = () => {
				if (!filterOk(event.moved)) {
					if (!event.forced) event._result = { bool: false };
					else event._result = "ai";
				} else {
					event._result = {
						bool: true,
						moved: event.moved,
					};
				}
				event.dialog.close();
				if (ui.confirm) ui.confirm.close();
				game.resume();
				_status.imchoosing = false;
				setTimeout(function () {
					ui.arena.classList.remove("choose-to-move");
				}, 500);
				resolve(event._result);
			};
			event.dialog.classList.add("scroll1");
			event.dialog.classList.add("scroll2");
			event.dialog.classList.add("fullwidth");
			if (list.length > 2) {
				ui.arena.classList.add("choose-to-move");
				event.dialog.classList.add("fullheight");
			}

			/**
			 * @type { Card[][] } 保存每次移动后的对应实体牌的位置
			 */
			event.moved = [];
			/**
			 * @type { HTMLDivElement[] } 所有可移动的buttons数组
			 */
			var buttonss = [];
			event.buttonss = buttonss;
			/**
			 * 是否处于拖拽动画中(禁止其他的选择，拖拽)
			 */
			event.isPlayingAnimation = false;
			// 初始化触摸点位置和元素偏移量
			var touchStartX = 0;
			var touchStartY = 0;
			var elementOffsetX = 0;
			var elementOffsetY = 0;
			var currentElement;
			// 首次触发move事件的元素
			var firstOnDragElement;
			/**
			 * 每次移动后更新数据
			 */
			var updateButtons = function () {
				for (var i of buttonss) {
					// 更新每次移动后的对应实体牌的位置
					event.moved[i._link] = get.links(Array.from(i.childNodes));
					// 更新这个buttons的提示文本
					if (typeof i.textPrompt == "function") i.previousSibling.innerHTML = '<div class="text center">' + i.textPrompt(event.moved[i._link]) + "</div>";
				}
				if (filterOk(event.moved)) {
					ui.create.confirm("o");
				} else {
					if (!event.forced) ui.create.confirm("c");
					else if (ui.confirm) ui.confirm.close();
				}
			};

			/**
			 * 确认是否是拖拽开始
			 *
			 * 按下时，是不能判断出是否拖拽开始的，得在move事件才可以
			 *
			 * @this buttons
			 * @param { TouchEvent | MouseEvent } e
			 */
			var dragStart = function (e) {
				if (event.isPlayingAnimation) return;
				// 左键按下
				if (e instanceof MouseEvent) {
					if (e.which != 1) return;
				}
				// 单个手指按下
				if (window.TouchEvent && e instanceof TouchEvent) {
					if (e.touches.length != 1) return;
				}
				// 判断按下的元素是否是card
				var cards = Array.from(this.children);
				var target = cards.find(card => {
					// Node.contains()
					return card.contains(e.target);
				});
				if (target) {
					if (!target.copy) {
						target.copy = target.cloneNode(true);
						target.copy.style.opacity = "0.75";
						target.copy.style.pointerEvents = "none";
					}
					touchStartX = (e instanceof MouseEvent ? e.clientX : e.touches[0].clientX) / game.documentZoom;
					touchStartY = (e instanceof MouseEvent ? e.clientY : e.touches[0].clientY) / game.documentZoom;
					elementOffsetX = target.getBoundingClientRect().x / game.documentZoom - touchStartX;
					elementOffsetY = target.getBoundingClientRect().y / game.documentZoom - touchStartY;
					currentElement = target;
					// e.stopPropagation();
				}
			};

			/**
			 * 判断出是否拖拽开始
			 *
			 * move事件是在button元素上监听的，而不是在dialog.content上。
			 *
			 * @this dialog
			 * @param { TouchEvent | MouseEvent } e
			 */
			var onDrag = function (e) {
				if (event.isPlayingAnimation) return;
				if (e instanceof MouseEvent) {
					if (e.which != 1) return;
				}
				if (window.TouchEvent && e instanceof TouchEvent) {
					if (e.touches.length != 1) return;
				}
				if (!currentElement || !currentElement.copy) return;
				if (!firstOnDragElement) {
					if (!currentElement.contains(e.target)) {
						return;
					} else {
						firstOnDragElement = currentElement;
					}
				}
				// 拖动离开了这个牌的区域，进行赋值
				// if (!currentElement.contains(e.target)) {

				// }
				// 移除高亮
				ui.selected.guanxing_button?.classList.remove("glow2");
				ui.selected.guanxing_button = currentElement;
				ui.selected.guanxing_button.classList.add("glow2");
				// 显示拖拽的元素
				/**
				 * @type { HTMLDivElement }
				 */
				var copy = currentElement.copy;
				if (!ui.window.contains(copy)) {
					copy.style.position = "absolute";
					copy.style.transition = "none";
					copy.style.zIndex = "100";
					copy.css({
						boxShadow: "0px 0px 7px 2px rgba(233, 30, 77, 0.95)",
					});
					ui.window.appendChild(copy);
				}
				e = e instanceof MouseEvent ? e : e.touches[0];

				const ex = e.clientX / game.documentZoom;
				const ey = e.clientY / game.documentZoom;
				copy.style.left = `${ex + elementOffsetX}px`;
				copy.style.top = `${ey + elementOffsetY}px`;
			};

			var dragEnd = function (e) {
				if (event.isPlayingAnimation) return;
				if (e instanceof MouseEvent) {
					if (e.which != 1) return;
				}
				if (window.TouchEvent && e instanceof TouchEvent) {
					if (e.changedTouches.length != 1) return;
				}
				firstOnDragElement = null;
				buttonss.forEach(btn => {
					Array.from(btn.children).forEach(element => {
						if (element.copy && ui.window.contains(element.copy)) {
							ui.window.removeChild(element.copy);
						}
					});
				});
				if (!ui.selected.guanxing_button?.copy) return;
				var clientX = (e instanceof MouseEvent ? e.clientX : e.changedTouches[0].clientX) / game.documentZoom;
				var clientY = (e instanceof MouseEvent ? e.clientY : e.changedTouches[0].clientY) / game.documentZoom;
				// 鼠标当前处于哪个元素上
				var target = document.elementFromPoint(clientX * game.documentZoom, clientY * game.documentZoom);
				// 相当于没移动，让它自己触发后续的click
				if (ui.selected.guanxing_button.contains(target)) return;
				// 停止拖拽的目标处于哪个button区域中
				var button = buttonss.find(b => {
					// Node.contains()
					return b.contains(target);
				});
				// 不能拖拽到区域外
				if (!button) return;
				var children = Array.from(button.children);
				// 与card交换位置
				var card = children.find(element => element.contains(target));
				// 判断是否可以移动
				if (!card) {
					if (!filterMove(ui.selected.guanxing_button, button._link, event.moved)) return;
				} else {
					if (!filterMove(card, ui.selected.guanxing_button, event.moved)) return;
				}
				debugger
				//后续这里可以增加拖动到空白位置的效果
				/*

			 if (拖动到空白) {
				game.$elementGoto().then(){
					delete ui.selected.guanxing_button;
					event.isPlayingAnimation = false;
					updateButtons();
				}
				return


			}

			*/
				// FLIP动画
				// first
				buttonss.forEach(btn => {
					Array.from(btn.children).forEach(element => {
						element.style.transition = "none";
						element._rect = element.getBoundingClientRect();
					});
				});
				// last
				// 如果拖拽到一个空区域内
				if (!button.hasChildNodes()) {
					button.appendChild(ui.selected.guanxing_button);
				} else if (!card) {
					// 判断是加在第一个还是最后一个
					if (children.length > 0) {
						var firstChild = children[0];
						if (clientX < firstChild.getBoundingClientRect().left / game.documentZoom) {
							button.insertBefore(ui.selected.guanxing_button, firstChild);
						} else button.appendChild(ui.selected.guanxing_button);
					} else button.appendChild(ui.selected.guanxing_button);
				} else {
					// 是交换而不是到card前面
					var par1 = ui.selected.guanxing_button.parentNode,
						ind1 = ui.selected.guanxing_button.nextSibling,
						par2 = card.parentNode,
						ind2 = card.nextSibling;
					ui.selected.guanxing_button.classList.remove("glow2");
					par1.insertBefore(card, ind1);
					par2.insertBefore(ui.selected.guanxing_button, ind2);
				}
				// invert
				buttonss.forEach(btn => {
					Array.from(btn.children).forEach(element => {
						element._rect2 = element.getBoundingClientRect();
						element.style.transform = `translateX(${(element._rect.left - element._rect2.left) / game.documentZoom}px) translateY(${(element._rect.top - element._rect2.top) / game.documentZoom}px)`;
					});
				});
				// play
				event.isPlayingAnimation = true;
				setTimeout(() => {
					Promise.race([
						new Promise(resolve => setTimeout(resolve, 700)),
						Promise.all(
							buttonss
								.map(btn => Array.from(btn.children))
								.flat(1)
								.map(element => {
									return new Promise(resolve => {
										element.classList.remove("glow2");
										element.style.transition = "";
										const transformValue = element.style.transform;
										if (transformValue !== "translateX(0px) translateY(0px)" && transformValue !== "") {
											element.style.transform = "translateX(0px) translateY(0px)";
											element.addEventListener(
												"transitionend",
												event => {
													// 确保 transitionend 事件是针对当前元素的 transform 属性
													if (event.propertyName === "transform") {
														resolve();
													}
												},
												{ once: true }
											);
										} else resolve();
									});
								})
						),
					]).then(() => {
						delete ui.selected.guanxing_button;
						event.isPlayingAnimation = false;
						updateButtons();
					});
				}, 0);
			};

			// 根据数据创建区域
			var tex = event.dialog.add('<div class="text center">' + list[0][0] + "</div>");
			tex.classList.add("choosetomove");

			event.dialog.classList.add("addNewRow");
			event.dialog.classList.add("fullheight");
			event.dialog.classList.remove("nobutton");
			let rowContainer = ui.create.div(".row-container", event.dialog.content);
			rowContainer.css({
				gridTemplateColumns: "5fr 1fr",
			});
			for (var i = 0; i < list.length; i++) {
				//var buttons = ui.create.div(".buttons", event.dialog.content);
				var buttons = ui.create.div(".item-container", rowContainer);
				buttons.css({
					justifyContent: "center",
					height: "100%",
					flexWrap: "wrap",
					alignContent: "flex-start",
				});
				buttons.addEventListener(lib.config.touchscreen ? "touchstart" : "mousedown", dragStart, true);
				event.dialog.addEventListener(lib.config.touchscreen ? "touchmove" : "mousemove", onDrag, true);
				event.dialog.addEventListener(lib.config.touchscreen ? "touchend" : "mouseup", dragEnd, true);
				buttonss.push(buttons);
				buttons.classList.add("popup");
				buttons.classList.add("guanxing");
				buttons._link = i;
				if (list[i][1]) {
					if (get.itemtype(list[i][1]) == "cards") {
						var cardsb = ui.create.buttons(list[i][1], "card", buttons);
						if (list[i][2] && typeof list[i][2] == "string") {
							for (var ij of cardsb) ij.node.gaintag.innerHTML = get.translation(list[i][2]);
						}
					} else if (list[i][1].length == 2) {
						ui.create.buttons(list[i][1][0], list[i][1][1], buttons);
					}
				}
				if (list[i][2] && typeof list[i][2] == "function") buttons.textPrompt = list[i][2];

			}
			var tex = event.dialog.add('<div class="text center">点击或拖动两张牌以交换位置；点击一张牌并点击其他区域或拖动到其他区域以移动卡牌</div>');
			tex.classList.add("choosetomove");

			event.dialog.open();
			updateButtons();

			event.custom.replace.button = function (button) {
				if (event.isPlayingAnimation) return;
				var node = button.parentNode;
				if (!buttonss.includes(node)) return;
				if (!ui.selected.guanxing_button) {
					ui.selected.guanxing_button = button;
					button.classList.add("glow2");
					return;
				}
				if (ui.selected.guanxing_button == button) {
					button.classList.remove("glow2");
					delete ui.selected.guanxing_button;
					return;
				}
			};
			event.custom.replace.confirm = function (bool) {
				if (event.isPlayingAnimation) return;
				event.buttonss.forEach(btn => {
					Array.from(btn.children).forEach(element => {
						if (element.copy && ui.window.contains(element.copy)) {
							ui.window.removeChild(element.copy);
							delete element.copy;
						}
					});
				});
				if (bool)
					event._result = {
						bool: true,
						moved: event.moved,
					};
				else event._result = { bool: false };
				event.dialog.close();
				if (ui.confirm) ui.confirm.close();
				game.resume();
				_status.imchoosing = false;
				setTimeout(function () {
					ui.arena.classList.remove("choose-to-move");
				}, 500);
				resolve(event._result);
			};

			game.pause();
			game.countChoose();
			event.choosing = true;
		});
	} else if (event.isOnline()) {
		result = await event.sendAsync();
	} else {
		result = "ai";
	}

	if (event.time) {
		game.broadcastAll(time => {
			lib.configOL.choose_timeout = time;
		}, event.time);
	}

	if ((!result || result == "ai" || (event.forced && !result.bool)) && event.processAI) {
		var moved = event.processAI(event.list);
		if (moved) {
			result = {
				bool: true,
				moved,
			};
		} else {
			result = { bool: false };
		}
	}

	event.result = result;
}

//complexSelect设置为false的choosebutton
lib.element.player.chooseButtonOL2 = function (list, callback, ai) {
	var next = game.createEvent("chooseButtonOL");
	next.list = list;
	next.setContent("chooseButtonOL2");
	next.ai = ai;
	next.callback = callback;
	next._args = Array.from(arguments);
	return next;
}
lib.element.content.chooseButtonOL2 = function () {
	"step 0";
	event.targets = event.list.slice();
	if (!_status.connectMode) {
		event.result = {};
		event.goto(7);
		return;
	}
	//ui.arena.classList.add('markhidden');
	for (var i = 0; i < event.list.length; i++) {
		var current = event.list[i];
		current[0].wait();
		if (current[0].isOnline()) {
			var target = current.shift();
			target.send(
				function (args, callback, switchToAuto, processAI) {
					//ui.arena.classList.add('markhidden');
					var next = game.me.chooseButton.apply(game.me, args);
					next.callback = callback;
					next.switchToAuto = switchToAuto;
					next.processAI = processAI;
					next.complexSelect = false;
					game.resume();
				},
				current,
				event.callback,
				event.switchToAuto,
				event.processAI
			);
			target._choose_button_ol = current;
			event.list.splice(i--, 1);
		} else if (current[0] == game.me) {
			event.last = current;
			event.last.shift();
			event.list.splice(i--, 1);
		}
	}
	"step 1";
	if (event.list.length) {
		var current = event.list.shift();
		event.target = current.shift();
		var next = event.target.chooseButton.apply(event.target, current);
		next.callback = event.callback;
		next.switchToAuto = event.switchToAuto;
		next.processAI = event.processAI;
		next.complexSelect = false;
	} else {
		event.goto(3);
	}
	"step 2";
	event.target.unwait(result);
	event.goto(1);
	"step 3";
	if (event.last) {
		var next = game.me.chooseButton.apply(game.me, event.last);
		next.callback = event.callback;
		next.switchToAuto = event.switchToAuto;
		next.processAI = event.processAI;
		next.complexSelect = false;
	} else {
		event.goto(5);
	}
	"step 4";
	game.me.unwait(result);
	"step 5";
	if (!event.resultOL) game.pause();
	"step 6";
	/*game.broadcastAll(function(){
		ui.arena.classList.remove('markhidden');
	});*/
	event.result = event.resultOL;
	event.finish();
	"step 7";
	if (event.list.length) {
		var current = event.list.shift();
		event.target = current.shift();
		var next = event.target.chooseButton.apply(event.target, current);
		next.callback = event.callback;
		next.switchToAuto = event.switchToAuto;
		next.processAI = event.processAI;
		next.complexSelect = false;
	}
	"step 8";
	event.result[target.playerid] = result;
	if (event.list.length) event.goto(7);
}

//choosetomove的多人互动
lib.element.player.chooseToMoveOL = function() {
	var next = game.createEvent("chooseToMoveOL");
	next.player = this;
	for (var i = 0; i < arguments.length; i++) {
		if (typeof arguments[i] == "boolean") {
			next.forced = arguments[i];
		} else if (typeof arguments[i] == "string") {
			next.prompt = arguments[i];
		}
	}
	debugger
	next.setContent("chooseToMoveOL");
	next.filterOk = function () {
		return true;
	};
	next.filterMove = function () {
		return true;
	};
	return next;
}

lib.element.content.chooseToMoveOL = function () {
	"step 0";
	event.targets = event.list.slice();
	if (!_status.connectMode) {
		event.result = {};
		event.goto(7);
		return;
	}
	debugger
	for (var i = 0; i < event.list.length; i++) {
		var current = event.list[i];
		current[0].wait();
		if (current[0].isOnline()) {
			var target = current.shift();
			target.send(
				function (args, callback, switchToAuto, processAI) {
					var next = game.me.chooseToMove().apply(game.me);
					next.callback = callback;
					next.switchToAuto = switchToAuto;
					next.processAI = processAI;
					next.complexSelect = true;
					next.prompt = args[0][0];
					next.list = args[0][1];
					game.resume();
				},
				current,
				event.callback,
				event.switchToAuto,
				event.processAI
			);
			target._choose_button_ol = current;
			event.list.splice(i--, 1);
		} else if (current[0] == game.me) {
			event.last = current;
			event.last.shift();
			event.list.splice(i--, 1);
		}
	}
	"step 1";
	if (event.list.length) {
		var current = event.list.shift();
		event.target = current.shift();
		var next = event.target.chooseToMove.apply(event.target);
		next.callback = event.callback;
		next.switchToAuto = event.switchToAuto;
		next.processAI = event.processAI;
		next.prompt = current[0][0];
		next.list = current[0][1];
	} else {
		event.goto(3);
	}
	"step 2";
	event.target.unwait(result);
	event.goto(1);
	"step 3";
	if (event.last) {
		var next = game.me.chooseToMove().apply(game.me);
		next.callback = event.callback;
		next.switchToAuto = event.switchToAuto;
		next.processAI = event.processAI;
		next.prompt = event.last[0][0];
		next.list = event.last[0][1];
	} else {
		event.goto(5);
	}
	"step 4";
	game.me.unwait(result);
	"step 5";
	if (!event.resultOL) game.pause();
	"step 6";
	event.result = event.resultOL;
	event.finish();
	"step 7";
	if (event.list.length) {
		var current = event.list.shift();
		event.target = current.shift();
		var next = event.target.chooseToMove.apply(event.target);
		next.callback = event.callback;
		next.switchToAuto = event.switchToAuto;
		next.processAI = event.processAI;
		next.prompt = current[0][0];
		next.list = current[0][1];
	}
	"step 8";
	event.result[target.playerid] = result;
	if (event.list.length) event.goto(7);
}

//钫酸酱的文本输入
lib.element.player.chooseSWText = function chooseText() {
	var next = game.createEvent('chooseSWText');
	for (var i = 0; i < arguments.length; i++) {
		if (typeof arguments[i] == 'boolean') {
			next.forced = arguments[i];
		} else if (Array.isArray(arguments[i])) {
			next.filterText = arguments[i]
		} else if (typeof arguments[i] == 'function') {
			if (next.ai) next.filterText = arguments[i];
			else next.ai = arguments[i];
		}
		else if (typeof arguments[i] == 'string') {
			get.evtprompt(next, arguments[i]);
		}
		else if (get.itemtype(arguments[i]) == 'dialog') {
			next.dialog = arguments[i];
		}
		else if (typeof arguments[i] == 'number') {
			next.max = arguments[i]
		}
		if (next.forced == undefined) next.forced = false;
	}
	next.player = this;
	next.setContent('chooseSWText');
	next._args = Array.from(arguments);
	next.forceDie = true;
	return next;
}
lib.element.content.chooseSWText = function chooseTextContent() {
	'step 0';
	if (event.isMine()) {
		if (event.dialog) {
			event.dialog.open();
		}
		else if (event.prompt) {
			event.dialog = ui.create.dialog(event.prompt);
			if (event.prompt2) {
				event.dialog.addText(event.prompt2, event.prompt2.length <= 20);
			}
		}
		event.result = {}
		const div = document.createElement('div');
		const input = div.appendChild(document.createElement('input'));
		input.style.background = 'while';
		input.style.filter = "progid:DXImageTransform.Microsoft.Alpha(style=3,opacity=50,finishOpacity=40)";
		input.style.opacity = "1"
		input.style.width = '100%';
		input.style.fontSize = '20px';
		input.style.textAlign = 'center';
		input.style.color = '#e328b7';
		input.addEventListener('keydown', e => e.stopPropagation());
		input.addEventListener('keyup', e => e.stopPropagation());
		input.placeholder = '请在此输入文本';
		input.setAttribute('maxlength', event.max);
		event.dialog.add(div);
		game.pause();
		game.countChoose();
		event.choosing = true;
		var button = ui.create.control('确定', () => {
			if (event.filterText) {
				if (typeof event.filterText == 'function') {
					event.filterText = event.filterText()
				}
				if (!event.filterText.contains(input.value)) {
					return alert('您输入的内容不合要求')
				}
			}
			event.result.bool = true
			event.result.text = input.value ? input.value : ''
			doClose()
		});
		if (!event.forced) {
			var cancel = ui.create.control('取消', () => {
				event.result.bool = false
				doClose()
			});
		}
		event.switchToAuto = () => {
			event.result = 'ai';
			doClose()
		};
		const doClose = () => {
			button.remove();
			if (cancel) cancel.remove();
			game.resume();
		}
	} else if (event.isOnline()) {
		event.send();
	} else {
		event.result = 'ai';
	}
	'step 1';
	if (event.result == 'ai') {
		if (event.ai) {
			event.value = event.ai(event.getParent(), player);
		}
		event.result = {}
		event.result.bool = (event.value != -1 || event.forced)
		if (event.result.bool) event.result.text = event.value
	}
	_status.imchoosing = false;
	event.choosing = false;
	if (event.dialog) event.dialog.close();
	event.resume();
}
